package com.example.interactactivity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    //定义要操作的控件需要的控件
    private EditText editHello;
    private Button bntSend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//初始化组件
        editHello = (EditText) findViewById(R.id.editHello);
        bntSend = (Button) findViewById(R.id.btnSend);
//定义事件监听代码
        bntSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//创建 Bundle 对象准备数据
                Bundle bundle = new Bundle();
                bundle.putInt("num", 1);
                bundle.putString("msg", editHello.getText().toString());
//创建 Intent 对象，向 Intent 对象添加数据
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtras(bundle);
//①用 startActivityForResult 方法启动新的 Activity
                startActivityForResult(intent, 1); //此处将 1 定义成静态变量更佳
            }
        });
    }

    //③接收并处理返回的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) { //若当前 Activity 可能由多处返回，此处分支将更有必要
            Bundle retBundle = data.getExtras();
            String retMsg = retBundle.getString("msg");
            editHello.setText("");
            editHello.setHint(" 收到回复：" + retMsg);
        }
    }
}